package com.cheetah.start.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * Describe: Servlet 工具类 Author: 就 眠 仪 式 CreateTime: 2019/10/23
 */
@Slf4j

public class ServletUtil {

    /**
     * 异步操作获取不到 Describe: 获取 HttpServletRequest 对象 Param null Return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * Describe: 获取 HttpServletResponse 对象 Param null Return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /**
     * Describe: 获取 HttpServletSession 对象 Param null Return HttpServletSession
     */
    public static HttpSession getSession() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest().getSession();
    }

    /**
     * Describe: 判断是否为 Ajax 请求 Param null Return HttpServletSession
     */
    public static Boolean isAjax(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Describe: Response 对象写出数据 Param: msg 消息数据 Return null
     */
    public static void write(String msg) throws IOException {
        HttpServletResponse response = getResponse();
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(msg);
    }

    /**
     * 获取查询参数
     */
    public static String getQueryParam() {
        return getRequest().getQueryString();
    }

    /**
     * 获取请求地址
     */
    public static String getRequestUri() {
        return getRequest().getRequestURI();
    }

    /**
     * 获取客户端地址
     */
    public static String getRemoteHost() {
        String remoteHost = getRequest().getRemoteHost();
        if ("0:0:0:0:0:0:0:1".equals(remoteHost)) {
            remoteHost = "127.0.0.1";
        }
        return remoteHost;
    }

    /**
     * 获取当前请求方法
     */
    public static String getMethod() {
        return getRequest().getMethod();
    }

    /**
     * 获取请求头
     */
    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    /**
     * 获取 UserAgent
     */
    public static String getAgent() {
        return getHeader("User-Agent");
    }

    /**
     * 获取浏览器类型
     */
    public static String getBrowser() {
        String userAgent = getAgent();
        if (userAgent.contains("Firefox")) {
            return "火狐浏览器";
        } else if (userAgent.contains("Chrome")) {
            return "谷歌浏览器";
        } else if (userAgent.contains("Trident")) {
            return "IE 浏览器";
        } else {
            return "你用啥浏览器";
        }
    }

    /**
     * 获取浏览器类型
     */
    public static String getSystem() {
        String userAgent = getAgent();
        if (userAgent.toLowerCase().contains("windows")) {
            return "Windows";
        } else if (userAgent.toLowerCase().contains("mac")) {
            return "Mac";
        } else if (userAgent.toLowerCase().contains("x11")) {
            return "Unix";
        } else if (userAgent.toLowerCase().contains("android")) {
            return "Android";
        } else if (userAgent.toLowerCase().contains("iphone")) {
            return "IPhone";
        } else {
            return "UnKnown, More-Info: " + userAgent;
        }
    }

    /**
     * 得到参数
     *
     * @param request 请求
     * @return {@link String}
     */
    public static String getParam(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String contentType = request.getContentType();
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(Arrays.toString(entry.getValue())).append(";");
        }
        try {
            if (contentType != null && contentType.contains(ContentType.JSON.getValue())) {
                BufferedReader reader = request.getReader();
                String line;
                while (StrUtil.isNotBlank(line = reader.readLine())) {
                    stringBuilder.append(line);
                }
            }
        } catch (IOException e) {
            log.error("日志打印异常", e);
        }
        return stringBuilder.toString();
    }

    public static String getBrowseInfo(HttpServletRequest request) {
        UserAgent parse = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String browserName = "";
        String version = "";
        OS os = null;
        if (parse != null) {
            Browser browser = parse.getBrowser();
            if (browser != null) {
                browserName = browser.getName();
            }
            version = parse.getVersion();
            os = parse.getOs();
        }
        return browserName + "|" + version + "|" + os;
    }
}
